<?php

class M_pages extends CI_Model {

	function __construct(){
		parent::__construct();
	}

	function pages_view($url){
		$sql="SELECT * FROM page WHERE lower(judul)='".strtolower($url)."'";

		$rs=$this->db->query($sql);
		if($rs->num_rows()){
			return $rs->row();
		}else{
			return "";
		}
	}

	function pages_list($search_text, $start, $end, $tglawal, $tglakhir){

		$sql="SELECT
				id,
				judul,
				isi,
				tag,
				publish,
				permalink
			FROM
				page
			WHERE id IS NOT NULL 
			";
		if($search_text != ''){
			$sql .= " AND ( lower(judul) LIKE '%".$search_text."%' 
				OR lower(isi) LIKE '%".$search_text."%'
			)";
		}
		if($tglawal != '' && $tglakhir != ''){
			$sql .= " AND page.created_date >= '".$tglawal."' AND page.created_date <= '".$tglakhir."' ";
		}
		$num_rows = $this->m_public_function->get_count_rows($sql);
		$sql .= " ORDER BY id DESC ";
		if($start != 0 && $end != 0){
			$sql.=" LIMIT $start, $end";
		}
		$query = $this->db->query($sql);

		if($num_rows > 0){
			$result = $query->result();
			$i = 0;
			foreach($result as $row){
				$data[$i] = $row;
				$i++;
			}
		}
		$final[] = array(
			"TotalRows"=>$num_rows,
			"results"=>$data
		);
		return json_encode($final);
	}

	function getDetail($id){
		$this->db->where('id', $id);
		$query = $this->db->get('page');

		$num_rows = $query->num_rows();
		if($num_rows > 0){
			return $query->row();
		}
	}
	
	function pages_save($params){
		extract($params);
		if($task == 'create'){
			$this->db->insert('page',$data);
		}else{
			$this->db->where('id', $id);
			$this->db->update('page',$data);
		}
		if($this->db->affected_rows()){
			return 1;
		}else{
			return 0;
		}
	}

	function pages_delete($id){
		$this->db->where('id',$id);
		$this->db->delete('page');
		if($this->db->affected_rows()){
			return 1;
		}else{
			return 0;
		}
	}
	function pages_switchpublish($id, $stats){
		$data = array(
			"publish"=>$stats
		);
		$this->db->where("id", $id);
		$this->db->update('page', $data);
		if($this->db->affected_rows()){
			return 1;
		}else{
			return 0;
		}
	}
}